<template>
  <div v-drag>
    <div class="mask" @click="closePopup(false)"></div>
    <div class="edit_box" v-loading="loading">
      <div class="box_head">
        <p>生成预支付订单</p>
        <i @click="closePopup(false)"></i>
      </div>
      <div class="box_body">
        <div class="line" v-if="step===1">
          <span class="lab"><i class="mark_icon" v-if="!$route.query.userId">*</i>用户：</span>
          <div>
            <userSelect @listenToUser="getUserId" :uId="userId" v-if="!$route.query.userId"/>
            <p v-else>{{$route.query.username}}</p>
          </div>
        </div>
        <div v-else>
          <div class="line">
            <div class="g_mb_10">
              <a class="common_btn el-icon-delete" @click="clearNum()"></a>
              <a class="common_btn el-icon-circle-plus-outline" @click="addProNum()"></a>
            </div>
          </div>
          <div>
            <div v-for="(link,index) in proNum" :key="index" class="input-box g_mb_10" id="link"
                 @mouseenter="showDel(index)" @mouseleave="delNum=null">
              <div class="input_box">
                <div class="select_box" ref="input">
                  <el-select
                    filterable
                    ref="linkName"
                    v-model="link.productId"
                    @change="judgeInfo"
                    :popper-append-to-body="false"
                    placeholder="请选择商品" @focus="getIndex($event,index)">
                    <span v-if="link.productId === ''">
                    <el-option
                      v-for="(item,index) in list"
                      :key="index"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                    </span>

                    <span v-else>
                    <el-option
                      v-for="(item,index) in finalProductList"
                      :key="index"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                    </span>

                  </el-select>
                </div>
                <div class="num_box">
                  <span class="minus_btn"  @click="deleteProduct(index)">
                    <i class="el-icon-minus" :class="{'lose':parseFloat(link.numbers) <=1}"></i>
                  </span>
                      <input class="num_show" type="number" v-model="link.numbers"  min="0"/>
                   <span class="plus_btn" @click="addProduct(index)">
                    <i class="el-icon-plus"></i>
                  </span>
                </div>
                <!--只有一条的时候，不显示删除-->
                <i class="delSingle el-icon-remove-outline" @click="delSingleInput(index)" v-if="index>0"></i>
              </div>
            </div>
          </div>
        </div>
        <p class="error_line" :class="{'specail_error':step===2}">{{ tipText }}</p>
      </div>
      <div class="box_foot" v-if="step===1">
        <span @click="closePopup(false)">取消</span>
        <span @click="setStep(2)">下一步</span>
      </div>
      <div class="box_foot" v-else>
        <span @click="step=1">上一步</span>
        <span @click="confirmEdit">确定</span>
      </div>
    </div>
  </div>
</template>

<script>
import {getAllProduct} from "@/api/config/product";
import {createData} from "@/api/data/user/order";

import userSelect from '../../../components/user/index.vue'

export default {
  components: {
    userSelect
  },
  data() {
    return {
      step:1,
      loading: false,
      tipText:'',
      userId:'',
      list:[],
      finalProductList:[],
      isFinal:false,
      proNum: [{
        numbers:1,
        productId:''
      }],
      test: [],
      delNum:null,
      isSame:false
    }
  },
  mounted() {
    if (this.$route.query.userId){
      this.userId = this.$route.query.userId;
    }
    this.getProduct();
  },
  methods:{
    getProduct(data){
      let queryParams = {
        display:1
      };
      if(data) {
        queryParams.productIds = data;
      }
      getAllProduct(queryParams).then((res)=>{
        this.list = res ? res: [];
        if(!this.isFinal) {
          this.finalProductList = res ? res :[];
          this.isFinal = true;
        }
      })
    },
    getIndex(e,index) {
      this.proNum[index].productId = '';
      this.getNewAllProduct();
    },
    getNewAllProduct() {
      // 重新获取列表
      let arr = []
      this.proNum.forEach((item,index)=> {
        if(item.productId !== '') {
          arr.push(item.productId)
        }
        return arr
      })
      arr = arr.join(',')
      this.getProduct(arr);
    },

    getUserId(e){
      this.userId = e;
      this.tipText = ''
    },

    setStep(type){
      if (type===2){
        if (this.userId===''){
          this.tipText = '请先选择订单用户'
        }else{
          this.step = type;
        }
      }
    },

    judgeInfo(){
      let that = this;
      that.tipText = '';
      that.isSame = false;
      for (let i = 0; i < that.proNum.length - 1; i++) {
        for (let j = i + 1; j < that.proNum.length; j++) {
          if (that.proNum[i].productId === that.proNum[j].productId) {
            that.tipText = '不能选择两种相同的商品';
            that.isSame = true;
          }
        }
      }
    },

    closePopup(refresh) {
      this.$emit('listenToChild',{refresh:refresh})
    },

    confirmEdit() {
      let that = this;
      if (that.isSame){
        that.tipText = '不能选择两种相同的商品';
      }else{
        let error = 0;
        that.proNum.forEach((item,index)=>{
          if (!item.productId) {
            that.$refs.input[index].className = 'error_border';
            that.tipText = '请选择商品或者删除不需要的商品';
            error ++;
          }
        })
        if (error===0){
          that.createUserOrder();
        }
      }
    },

    createUserOrder(){
      this.loading = true;
      let param = {
        userId:this.userId,
        dataUserOrderProductVoList:this.proNum
      }
      createData(param).then(res=>{
        this.$message.success({
          message:'操作成功',
          duration:1500
        });
        this.closePopup(true);
        this.loading = false;
      }).catch((e)=>{
        this.loading = false;
      })
    },

    deleteProduct(index){
      let num = this.proNum[index].numbers;
      this.proNum[index].numbers = parseFloat(num) <=1?1: parseFloat(num)-1;
    },

    addProduct(index){
      this.proNum[index].numbers = parseFloat(this.proNum[index].numbers) + 1;
    },

    /*添加*/
    addProNum() {
      let cope = {numbers:1,productId:''};
      this.proNum.push(cope);
      this.tipText = '';
    },

    /*清除*/
    clearNum() {
      this.proNum = [];
      for (const i in this.$refs.input) {
        this.$refs.input[i].className = ''
      }
      let cope = {numbers:1,productId:''};
      this.proNum.push(cope);
      this.tipText = '';
    },

    // 单个删除
    delSingleInput(index) {
      this.proNum.splice(index, 1);
      this.tipText = '';
    },

    showDel(index) {
      this.delNum = index + 1;
      /*只有一条的时候，不加删除文字，可清空*/
      if (this.proNum.length === 1) {
        this.delNum = null
      }
    },
  }
}
</script>

<style scoped>
  .box_body{
    min-height: 400px;
  }
 .input_box {
  display: flex;
  align-items: center;
  position: relative;
  /*overflow: hidden;*/
  /*width: 400px;*/
}

* {
  box-sizing: border-box;
}

.g_mb_10 {
  margin-bottom: 10px;
}

a {
  text-decoration: none;
}

.common_btn {
  font-size: 24px;
  cursor: pointer;
  color: #6687f9;
  margin-right: 5px;
}

.delSingle {
  position: absolute;
  top: 10px;
  right: 38px;
  cursor: pointer;
  font-size: 22px;
  color: #e40000;
}

 .num_box  {
   border: 1px solid #DCDFE6;
   border-radius: 4px;
   overflow: hidden;
   margin-left: 30px;
 }

.minus_btn,.plus_btn {
  width: 34px;
  display: inline-block;
  height:34px;
  line-height:34px;
  text-align:center ;
  cursor: pointer;
}

 .minus_btn i,.plus_btn i{
   color: #6687f9;
 }

.minus_btn {
  border-right: 1px solid #DCDFE6;
}

.plus_btn {
  border-left: 1px solid #DCDFE6;
}

.lose {
  color: #DCDFE6!important;
}

.num_show {
  max-width: 80px;
  min-width: 40px;
  line-height: 34px;
  text-align:center ;
  border: none;
  outline: none;
}
 .specail_error {
   padding-left: 0;
   margin-top: 30px;
 }
</style>
